package com.todo.servlet;

import com.todo.dao.TodoDAO;
import com.todo.model.Todo;
import com.todo.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/todos/*")
public class TodoServlet extends HttpServlet {
    private TodoDAO todoDAO;
    private SimpleDateFormat dateFormat;

    public void init() {
        todoDAO = new TodoDAO();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();
        if (action == null) {
            action = "/list";
        }

        try {
            switch (action) {
                case "/list":
                    listTodos(request, response);
                    break;
                case "/edit":
                    showEditForm(request, response);
                    break;
                case "/new":
                    showNewForm(request, response);
                    break;
                default:
                    listTodos(request, response);
                    break;
            }
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();

        try {
            switch (action) {
                case "/insert":
                    insertTodo(request, response);
                    break;
                case "/update":
                    if (request.getParameter("completed") != null) {
                        updateTodoStatus(request, response);
                    } else {
                        updateTodo(request, response);
                    }
                    break;
                case "/delete":
                    deleteTodo(request, response);
                    break;
            }
        } catch (SQLException | ParseException ex) {
            throw new ServletException(ex);
        }
    }

    private void listTodos(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        List<Todo> todos = todoDAO.getAllTodos(user.getId());
        request.setAttribute("todos", todos);
        request.setAttribute("currentTime", System.currentTimeMillis());
        request.getRequestDispatcher("/WEB-INF/views/todo-list.jsp").forward(request, response);
    }

    private void showNewForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/views/todo-form.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        Long id = Long.parseLong(request.getParameter("id"));
        Todo todo = todoDAO.getTodoById(id);
        request.setAttribute("todo", todo);
        request.getRequestDispatcher("/WEB-INF/views/todo-form.jsp").forward(request, response);
    }

    private void insertTodo(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException, ParseException {
        // 从session获取当前登录用户
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        String title = request.getParameter("title");
        String description = request.getParameter("description");
        String dueDateStr = request.getParameter("dueDate");
        
        Todo todo = new Todo();
        todo.setTitle(title);
        todo.setDescription(description);
        todo.setUserId(user.getId());  // 设置用户ID
        if (dueDateStr != null && !dueDateStr.isEmpty()) {
            Date dueDate = dateFormat.parse(dueDateStr);
            todo.setDueDate(dueDate);
        }
        
        todoDAO.addTodo(todo);
        response.sendRedirect("list");
    }

    private void updateTodo(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException, ParseException {
        // 获取当前用户
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }

        Long id = Long.parseLong(request.getParameter("id"));
        String title = request.getParameter("title");
        String description = request.getParameter("description");
        boolean completed = "on".equals(request.getParameter("completed"));
        String dueDateStr = request.getParameter("dueDate");
        
        Todo todo = todoDAO.getTodoById(id);
        if (todo != null && todo.getUserId().equals(user.getId())) {
            todo.setTitle(title);
            todo.setDescription(description);
            todo.setCompleted(completed);
            if (dueDateStr != null && !dueDateStr.isEmpty()) {
                Date dueDate = dateFormat.parse(dueDateStr);
                todo.setDueDate(dueDate);
            }
            
            todoDAO.updateTodo(todo);
            response.sendRedirect("list");
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    }

    private void deleteTodo(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        Long id = Long.parseLong(request.getParameter("id"));
        
        // 获取当前用户
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        // 确保只能删除自己的待办事项
        Todo todo = todoDAO.getTodoById(id);
        if (todo != null && todo.getUserId().equals(user.getId())) {
            todoDAO.deleteTodo(id, user.getId());  // 修改删除方法，添加用户ID验证
            response.sendRedirect("list");
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    }

    private void updateTodoStatus(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        Long id = Long.parseLong(request.getParameter("id"));
        boolean completed = Boolean.parseBoolean(request.getParameter("completed"));
        
        // 获取当前用户
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        
        Todo todo = todoDAO.getTodoById(id);
        if (todo != null) {
            todo.setCompleted(completed);
            todo.setUserId(user.getId()); // 确保设置了userId
            todoDAO.updateTodo(todo);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
} 